//
//  PKRequestManger.m
//  A 片刻
//
//  Created by lanou3g on 21/7/15.
//  Copyright (c) 2015年 lanou3g11. All rights reserved.
//

#import "MYRequestManger.h"

@implementation MYRequestManger
- (void)manager:(RequestType)postOrGet RequestWith:(NSString *)urlStr parDic:(NSDictionary*)parDic finish:(requestFinish)finish error:(requestError)error
{
    self.requestFinish = finish;
    self.requestError = error;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    
    if (postOrGet == POST) {
        //修改系统默认的GET为POST
        [request setHTTPMethod:@"POST"];
        if (parDic) {
            //2进制流拼接
             [request setHTTPBody:[self dicToHTTPBody:parDic]];
        }
    }
//    [NSURLConnection connectionWithRequest:request delegate:self];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}
+ (void)manager:(RequestType)postOrGet RequestWith:(NSString *)urlStr parDic:(NSDictionary*)parDic finish:(requestFinish)finish error:(requestError)error
{
    MYRequestManger *manage = [[MYRequestManger alloc]init];
    [manage manager:postOrGet RequestWith:urlStr parDic:parDic finish:finish error:error];
}

- (NSData *)dicToHTTPBody:(NSDictionary*)dic{
    
    NSMutableString *dataStr = [NSMutableString string];
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"&%@=%@",key,dic[key]];
        [dataStr appendString:str];
        
    }
    //接口的前面第一个没有& 所以去掉一个
    [dataStr deleteCharactersInRange:NSMakeRange(0, 1)];
    
    return [dataStr dataUsingEncoding:NSUTF8StringEncoding];
}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
    self.requestFinish(_data);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.requestError(error);
}


@end
